package com.sinopec.scandevice.presenter

import android.content.Intent
import android.net.Uri
import android.os.Environment
import android.provider.Settings
import com.azhon.appupdate.listener.OnDownloadListenerAdapter
import com.azhon.appupdate.manager.DownloadManager
import com.sinopec.basemodule.BuildConfig
import com.sinopec.basemodule.base.AppManager
import com.sinopec.basemodule.utils.ToastUtils
import com.sinopec.scandevice.MyApp
import com.sinopec.scandevice.R
import com.sinopec.scandevice.constants.CustomAppUpdateContract
import java.io.File


/**
 * @Description: 本地更新
 * @ClassName: CustomAppUpdatePresenter
 * @author lwj
 */
class CustomAppUpdatePresenter constructor(view: CustomAppUpdateContract.View) :
    CustomAppUpdateContract.Presenter(view) {

    private var downloadManager: DownloadManager? = null
    private var downloadApkUrl: String? = null

    //存储权限未授予
    override fun onStoragePermissionNotGranted() {
        ToastUtils.showToast("该功能需要存储权限.")

        val packageURI: Uri = Uri.parse("package:${MyApp.getInstance().packageName}")
        val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI)

        val lastActivity = AppManager.getInstance().topActivity
        lastActivity.startActivity(intent)
    }

    //开始执行下载流程
    override fun initDownloadListener(appUpdateUrl: String?) {
        customUpdateApp(appUpdateUrl)
    }

    override fun cancelDownloadListener() {
        downloadManager?.cancel()
    }

    override fun onInstall() {
        try {
            downloadManager?.install()
        } catch (e: Exception) {
            e.printStackTrace()
            customUpdateApp(downloadApkUrl)
        }
    }

    private fun customUpdateApp(appUpdateUrl: String?) {
        downloadApkUrl = appUpdateUrl
        downloadManager = DownloadManager.Builder(mView.context).run {
            apkUrl(appUpdateUrl ?: "")
            apkName(downloadApkName())
            smallIcon(if (BuildConfig.DEBUG) R.drawable.app_logo_debug else R.drawable.app_logo)
            onDownloadListener(downloadListener)
            showBgdToast(false)
            build()
        }
        downloadManager?.download()
    }

    private val downloadListener = object : OnDownloadListenerAdapter() {
        override fun downloading(max: Int, progress: Int) {
            if (null != mView) {
                val current = ((progress / max.toDouble()) * 100).toInt()
                mView.refreshDownLoadProgress(current)
            }
        }

        override fun error(e: Throwable) {
            ToastUtils.showToast("下载出错，请稍候重试")

            if (null != mView) {
                mView.downloadErrorRefreshUi()
            }
        }
    }

    private fun downloadApkName(): String {
        return "${System.currentTimeMillis()}.apk"
    }

    private fun downloadFilePath(): String {
        return mView.context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)?.absolutePath + File.separator + downloadApkName()
    }
}